/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2023-11-28 21:22:37
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2023-12-14 14:57:51
 * @FilePath: \sample_project\components\get_time.c
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
#include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_log.h"
#include <sys/time.h>
#include "get_time.h"

uint64_t system_timestamp;

void delay_ms(uint32_t millisecond)
{
    vTaskDelay(millisecond);
}

void set_system_time(uint64_t timestamp)
{
    static const char *TAG = "TimeSetting";
    struct timeval tv;
    tv.tv_sec = timestamp / 1000;           // 将毫秒转换为秒
    tv.tv_usec = (timestamp % 1000) * 1000; // 将剩余的毫秒转换为微秒
    if (settimeofday(&tv, NULL) == 0)
    {
        ESP_LOGI(TAG, "System time set successfully");
    }
    else
    {
        ESP_LOGE(TAG, "Failed to set system time");
    }
}

// 获取当前的系统时间戳并存入全局变量system_timestamp
void get_time(uint64_t *timestamp)
{
    static const char *TAG = "RTC";
    time_t second;
    struct tm *datetime;
    tzset();
    time(&second);
    datetime = localtime(&second);
    time_t ts = mktime(datetime);
    *timestamp = (uint64_t)ts; // 转换为时间戳
    // ESP_LOGI(TAG, "The current time is: %04d/%02d/%02d %02d:%02d:%02d.\n"
    //                "The timestamp is %13lld \n",  // 修正这一行
    //          datetime->tm_year + 1900, datetime->tm_mon + 1, datetime->tm_mday,
    //          datetime->tm_hour, datetime->tm_min, datetime->tm_sec, (long long)*timestamp);  // 修正这一行
}

void rtc_task_example(void *arg)
{
    static const char *TAG = "RTC";
    get_time(&system_timestamp);
    ESP_LOGI(TAG, "The timestamp is %013lld \n", (long long)system_timestamp); // 修正这一行
    while (1)
    {
        get_time(&system_timestamp);
        delay_ms(10);
    }
}

void print_system_time(void)
{
    static const char *TAG = "TimeSetting";
    struct timeval tv;
    struct tm *datetime;

    gettimeofday(&tv, NULL);
    datetime = localtime(&tv.tv_sec);
    datetime->tm_hour += 8;
    ESP_LOGI(TAG, "The current time is: %04d/%02d/%02d %02d:%02d:%02d.%06ld",
             datetime->tm_year + 1900, datetime->tm_mon + 1, datetime->tm_mday,
             datetime->tm_hour, datetime->tm_min, datetime->tm_sec, tv.tv_usec);
}

// xTaskCreate(rtc_task_example, "rtc_task_example", 4096, NULL, 10, NULL);
